package zhuyun.code

import java.awt.BorderLayout
import java.awt.Container
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.*

fun main(args:Array<String>){
    val x = 100
    val y = 100
    val xiaoming = Customer("小明",x,y)
    val xiaohong = Customer("小红",x+250,y)
    val xiaofang = Customer("小方",x+500,y)
    val medium = EstateMedium()
    medium.register(xiaoming)
    medium.register(xiaofang)
    medium.register(xiaohong)
    xiaofang.send("大家好，我是小方")
    xiaohong.send("大家好，我是小红")
    xiaoming.send("大家好，我是小明")

}
interface Medium{
    fun register(member:Customer)
    fun relay(from:String, ad:String)
}

class EstateMedium:Medium{
    private val members = mutableListOf<Customer>()
    override fun register(member: Customer) {
        members.add(member)
        member.medium = this
    }

    override fun relay(from: String, ad: String) {
        members.forEach {
            if(!it.identifer.equals(from)){
                it.receive(from,ad)
            }
        }
    }

}

class Customer(val identifer:String):JFrame(),ActionListener{
    lateinit var medium:Medium
    private lateinit var sendText:JTextField
    private lateinit var receiveArea:JTextArea
    constructor(identifer: String,x:Int,y:Int) : this(identifer) {
        createClientWindow(x,y)
    }
    fun createClientWindow(x:Int,y:Int){
        title = identifer
        val cp = contentPane
        sendText = JTextField(18)
        receiveArea = JTextArea(10,18)
        receiveArea.isEditable = false
        val p1 = JPanel()
        p1.border = BorderFactory.createTitledBorder("接受内容")
        p1.add(receiveArea)
        val sp = JScrollPane(p1)
        cp.add(sp,BorderLayout.NORTH)
        val p2 = JPanel()
        p2.border = BorderFactory.createTitledBorder("发送内容")
        p2.add(sendText)
        cp.add(p2,BorderLayout.SOUTH)
        sendText.addActionListener(this)
        this.setLocation(x,y)
        this.setSize(250,330)
        this.isResizable = false
        this.defaultCloseOperation =JFrame.EXIT_ON_CLOSE
        this.isVisible = true


    }
    fun receive(from:String, ad:String){
        receiveArea.append("${from}说:${ad}\n")
        receiveArea.caretPosition = receiveArea.text.length
    }
    fun send(ad:String){
        receiveArea.append("${identifer}说:${ad}\n")
        receiveArea.caretPosition = receiveArea.text.length
        medium.relay(identifer,ad)
    }

    override fun actionPerformed(e: ActionEvent?) {
        val text = sendText.text
        sendText.text=""
        send(text)
    }



}